package com.huika.renrench.control.my.account;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.params.FileTypeParam;
import com.huika.lib.utils.FileUtils;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.Constant;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.activity.LoginActivity;
import com.huika.renrench.control.login.event.LoginEvent;
import com.huika.renrench.control.login.event.LogoutEvent;
import com.huika.renrench.control.main.shoptf.gallery.ImageDetailAct;
import com.huika.renrench.control.main.shoptf.gallery.ProductImageArray;
import com.huika.renrench.control.my.bank.activity.MyBankCardActivity;
import com.huika.renrench.control.my.certification.activity.AlreadyCertificationActivity;
import com.huika.renrench.control.my.certification.activity.CertificationActivity;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.ImageBeanPic;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.FileTool;
import com.huika.renrench.utils.ImageTools;
import com.huika.renrench.utils.LoginUtils;
import com.huika.renrench.utils.PhoneUtil;
import com.huika.renrench.view.MMAlertDialog;
import com.huika.renrench.view.RoundImageView;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.uploadpop.ActionPopupItem;
import com.huika.renrench.view.uploadpop.ButtomPopup;
import com.huika.renrench.view.uploadpop.ButtomPopup.OnPopupItemOnClickListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import de.greenrobot.event.EventBus;

public class AccountInfoActivity extends BaseAct implements OnPopupItemOnClickListener {
	private RelativeLayout layoutHdImg;
	private RoundImageView ivHd;
	private RelativeLayout layoutCertificate;
	private TextView tvCertificate;
	private RelativeLayout layoutPhone;
	private RelativeLayout layoutCard;
	private RelativeLayout layoutLoginPwd;
	private RelativeLayout layoutPayPwd;
	private RelativeLayout layoutExit;
	private TextView tvPhone;
	private TextView tvPTitle;
	
	private String phone;

	private LinearLayout mMainLinear;
	/** 选取图片路径 */
	private File picFile;
	UserModel userModel;
	public DisplayImageOptions options;
	
	private ImageBeanPic ImageBeanPic;
	
	private TextView set_code_tv;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_account_info);
		EventBus.getDefault().register(this);
	}

	public void onEventMainThread(LoginEvent loginEvent) {
		if (loginEvent.getLoginStatus() == 1) {
			layoutExit.setVisibility(View.VISIBLE);
			initContent();
		} else {
			showActivity(aty, LoginActivity.class);
			this.finish();
		}
	}

	public void onEventMainThread(LogoutEvent logoutEvent) {
		if (logoutEvent.getLogonStatus() == 1) {
			layoutExit.setVisibility(View.GONE);
			this.finish();
		}
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	protected void initWidget() {
		TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1, -1, R.string.title_accont_info);
		titleBarHelper.setLeftMsg(R.string.common_index_my);
		mMainLinear = (LinearLayout) findViewById(R.id.layout_main_aai);
		layoutHdImg = (RelativeLayout) findViewById(R.id.layout_hdimg_aai);
		ivHd = (RoundImageView) findViewById(R.id.riv_hdimg_aai);
		layoutCertificate = (RelativeLayout) findViewById(R.id.layout_certificate_aai);
		tvCertificate = (TextView) findViewById(R.id.tv_certificate_aai);
		layoutPhone = (RelativeLayout) findViewById(R.id.layout_phone_aai);
		layoutCard = (RelativeLayout) findViewById(R.id.layout_card_aai);
		layoutLoginPwd = (RelativeLayout) findViewById(R.id.layout_loginpwd_aai);
		layoutPayPwd = (RelativeLayout) findViewById(R.id.layout_paypwd_aai);
		layoutExit = (RelativeLayout) findViewById(R.id.layout_exit_aai);
		tvPhone = (TextView) findViewById(R.id.tv_phone_aai);
		tvPTitle = (TextView) findViewById(R.id.tv_ptitle_aai);
		 
		set_code_tv= (TextView) findViewById(R.id.set_code_tv); 
		

		ivHd.setOnClickListener(this);
		layoutHdImg.setOnClickListener(this);
		layoutCertificate.setOnClickListener(this);
		layoutPhone.setOnClickListener(this);
		layoutCard.setOnClickListener(this);
		layoutLoginPwd.setOnClickListener(this);
		layoutPayPwd.setOnClickListener(this);
		layoutExit.setOnClickListener(this);
		
		// 创建头像下载
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.img_user_pic).showImageForEmptyUri(R.drawable.img_user_pic)
				.showImageOnFail(R.drawable.img_user_pic).cacheInMemory(true)// 开启内存缓存
				.cacheOnDisk(true) // 开启硬盘缓存
				.resetViewBeforeLoading(false).build();

	}

	@Override
	protected void onResume() {
		super.onResume();
		initContent();
	}

	private void initContent() {
		for (int i = 0; i < imgUrls.size(); i++) {
			imgUrls.remove(i);
		}
		userModel = GlobalApp.userModel;
		if (userModel.getIsSetPayPwd()==1) {
			set_code_tv.setText("修改交易密码");
		}else{
			set_code_tv.setText("设置交易密码");
		}
		
		phone = userModel.getPhone();
		if (phone != null && !TextUtils.isEmpty(phone)) {
			tvPTitle.setText("修改手机号");
		} else {
			tvPTitle.setText("绑定手机号");
		}
		if (userModel != null) {
			String hdUrl = userModel.getHeadImg();
			if (hdUrl != null && !TextUtils.isEmpty(hdUrl)) {
				ImageLoader.getInstance().displayImage(hdUrl,ivHd, options);
				ProductImageArray ImgArray = new ProductImageArray();
				ImgArray.setBigImageUrl(userModel.getBigImgUrl());
				ImgArray.setImageUrl(hdUrl);
				imgUrls.add(ImgArray);
			}
			String realName = userModel.getRealName();
			String idCard = userModel.getIdCard();
			if (realName != null && !TextUtils.isEmpty(realName) && idCard != null && !TextUtils.isEmpty(idCard)) {
				tvCertificate.setText("已认证");
			} else {
				tvCertificate.setText("未认证");
			}
			String phone = userModel.getPhone();
			if (phone != null && !TextUtils.isEmpty(phone)) {
				tvPhone.setText(PhoneUtil.TelPhoneStr(phone));
			}
			
			if (userModel.getIsSetPayPwd()==1) {
				set_code_tv.setText("修改交易密码");
			}else{
				set_code_tv.setText("设置交易密码");
			}
		}else {
			ivHd.setImageResource(R.drawable.img_user_pic);
			tvCertificate.setText("未认证");
			tvPhone.setText("");
		}
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.riv_hdimg_aai:
			showGallery();
			break;
		case R.id.layout_hdimg_aai:
			showPicSelectPop();
			break;
		case R.id.layout_certificate_aai:
			if (tvCertificate.getText().toString().equals("已认证")) {
				showActivity(AccountInfoActivity.this, AlreadyCertificationActivity.class);
			}else {
				showActivity(AccountInfoActivity.this, CertificationActivity.class);
			}
			
			break;
		case R.id.layout_phone_aai:
			if (phone != null && !TextUtils.isEmpty(phone)) {
				showActivity(AccountInfoActivity.this, ModifyPhoneActivity.class);
			} else {
				Intent intent = new Intent(aty, SetNewPhoneActivity.class);
				intent.putExtra("key", "000000");
				showActivity(aty, intent);
			}
			break;
		case R.id.layout_card_aai:
			showActivity(AccountInfoActivity.this, MyBankCardActivity.class);
			break;
		case R.id.layout_loginpwd_aai:
			showActivity(AccountInfoActivity.this, ModifyLoginPwdActivity.class);
			break;
		case R.id.layout_paypwd_aai:
			showActivity(AccountInfoActivity.this, SetPayPwdActivity.class);
			break;
		case R.id.layout_exit_aai:
			exit();
			break;
		default:
			break;
		}
	}

	private Dialog exitDialog;// 退出提示对话框

	private void exit() {
		exitDialog = MMAlertDialog.createSoftwareUpdate(this, "您确认要退出吗？", new OnClickListener() {

			@Override
			public void onClick(View v) {
				exitDialog.cancel();
			}
		}, new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginUtils.logout();
			}
		});
		exitDialog.show();
	}

	/** 底部图片选择 */
	private ButtomPopup buttomPopup;
	private String[] buttomSpiners = { "拍照", "从手机相册中选择" };

	/**
	 * @Description:用户图像更改
	 * 
	 */
	private void showPicSelectPop() {
		if (null == buttomPopup) {
			buttomPopup = new ButtomPopup(AccountInfoActivity.this, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, this);
		} else {
			buttomPopup.cleanAction();
		}
		buttomPopup.addAction(new ActionPopupItem(buttomSpiners[0], false, Constant.ACTIVITY_RESULT_CROPCAMARA_WITH_DATA, false));
		buttomPopup.addAction(new ActionPopupItem(buttomSpiners[1], false, Constant.ACTIVITY_RESULT_CROPIMAGE_WITH_DATA, false));
		buttomPopup.show(mMainLinear);
	}

	@Override
	public void onPopupItemClick(ActionPopupItem item, int position) {
		switch (item.mItemValue) {
		case Constant.ACTIVITY_RESULT_CROPCAMARA_WITH_DATA:
			// 拍照片
			takePhoto();
			break;
		case Constant.ACTIVITY_RESULT_CROPIMAGE_WITH_DATA:
			// 从相册选择
			selectPhoto();
			break;
		default:
			break;
		}

	}

	private void takePhoto() {
		if (!ImageTools.isSDCardExist()) {
			showToastMsg("sd卡不可用");
			return;
		}
		Intent cameraIntent = null;
		picFile = ImageTools.initTempFile();
		cameraIntent = ImageTools.getTakeCameraIntent(Uri.fromFile(picFile));
		startActivityForResult(cameraIntent, Constant.ACTIVITY_RESULT_CROPCAMARA_WITH_DATA);
	}

	private void selectPhoto() {
		Intent photoIntent = null;
		picFile = ImageTools.initTempFile();
		photoIntent = ImageTools.cropPhotoOfCompressFromGalleryIntent2(Uri.fromFile(picFile));
		startActivityForResult(photoIntent, Constant.ACTIVITY_RESULT_CROPIMAGE_WITH_DATA);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case Constant.ACTIVITY_RESULT_CROPCAMARA_WITH_DATA: // 拍照
			Intent intent = ImageTools.cropPhotoOfCompressIntent(Uri.fromFile(picFile));
			startActivityForResult(intent, Constant.ACTIVITY_RESULT_CROPIMAGE_WITH_DATA);
			break;
		case Constant.ACTIVITY_RESULT_CROPIMAGE_WITH_DATA:
			if (null == data) {
				return;
			}
			if (picFile == null) {
				showToastMsg("选择头像失败");
				return;
			}
			if (TextUtils.isEmpty(picFile.toString()) || !picFile.exists()) {
				showToastMsg("没有选择到图片");
				return;
			}
			uploadHd();
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 上传头像
	 */
	private void uploadHd() {
		showLoadingDialog("上传头像");
		executeUpdateBackgInfoList();
	}

	/** 获取网络数据,刷新用户信息 */
	private void executeUpdateBackgInfoList() {
		try {
		FormResultRequest<ImageBeanPic> request = new FormResultRequest<ImageBeanPic>(UrlConstants.UPLOADIMG, getUpdatePickgResp, this, new TypeToken<RequestResult<ImageBeanPic>>() {}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();//
		ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());//userId
		if(picFile != null) {
		ajaxParams.putStringTypeParam("validateKey", FileTool.getMD5FromFile(picFile));
		ajaxParams.put(new FileTypeParam("fileName", picFile.getPath(), FileUtils.getMimeType(Uri.fromFile(new File(picFile.getPath())).toString())));
		}
		request.setRequestParams(ajaxParams);
		executeRequest(request);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Listener<RequestResult<ImageBeanPic>> getUpdatePickgResp = new Listener<RequestResult<ImageBeanPic>>() {

		@Override
		public void onResponse(RequestResult<ImageBeanPic> result) {
			if (result.flag == 1) {
				if (result != null && result.getRs() != null) {
					ImageBeanPic = result.getRs();
     				executeUpdateBackgInfoList1();
				}
//				showToastMsg(result.msg);
			} else {
				showToastMsg(result.msg);
			}
//			dismissLoadingDialog();
			if (mOverlayLayout != null)
				hideOverLay();
		}
	};
	
	/** 获取网络数据,刷新用户信息 */
	private void executeUpdateBackgInfoList1() {
		try {
		FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.UPLOADUSERIMG, getUpdatePickgResp1, this, new TypeToken<RequestResult<String>>() {}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();//
		ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());//userId
		if(picFile != null) {
		ajaxParams.putStringTypeParam("validateKey", FileTool.getMD5FromFile(picFile));
//		ajaxParams.put(new FileTypeParam("fileName", picFile.getPath(), FileUtils.getMimeType(Uri.fromFile(new File(picFile.getPath())).toString())));
		}
		request.setRequestParams(ajaxParams);
		executeRequest(request);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Listener<RequestResult<String>> getUpdatePickgResp1 = new Listener<RequestResult<String>>() {

		@Override
		public void onResponse(RequestResult<String> result) {
			if (result.flag == 1) {
					if (userModel != null && ImageBeanPic!=null) {
						userModel.setHeadImg(ImageBeanPic.getImageUrl());
						GlobalApp.userModel = userModel;
					}
					initContent();
				showToastMsg(result.msg);
			} else {
				showToastMsg(result.msg);
			}
			dismissLoadingDialog();
			if (mOverlayLayout != null)
				hideOverLay();
		}
	};
	
	protected List<ProductImageArray> imgUrls  = new ArrayList<ProductImageArray>();

	private void showGallery() {
		if (imgUrls.size()==0) {
			return;
		}
			Bundle bundle = new Bundle();
			bundle.putParcelableArrayList("imageListBean",
					(ArrayList<? extends Parcelable>) imgUrls);
			bundle.putString("imageDetailCheck", imgUrls.get(0)
					.getBigImageUrl());
			Intent intent = new Intent(this, ImageDetailAct.class);
			intent.putExtras(bundle);
			startActivity(intent);

	}

}
